package net.lab1024.sa.admin.module.business.pdf.controller;

import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.annotation.Resource;
import net.lab1024.sa.admin.module.business.pdf.service.PdfDocumentService;
import net.lab1024.sa.admin.module.business.pdf.service.PdfDocumentContentService;
import net.lab1024.sa.admin.module.business.pdf.service.PdfParseService;
import net.lab1024.sa.admin.module.business.pdf.util.OcrConfigChecker;
import net.lab1024.sa.admin.config.PdfConfig;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import net.lab1024.sa.admin.module.business.pdf.domain.entity.PdfDocumentContentEntity;
import net.lab1024.sa.admin.module.business.pdf.domain.entity.PdfDocumentEntity;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import java.util.stream.Collectors;

/**
 * PDF文档管理
 *
 * @Author 1024创新实验室
 */
@RestController
@Tag(name = "PDF文档管理")
@RequestMapping("/pdf/document")
public class PdfDocumentController {

    @Resource
    private PdfDocumentService pdfDocumentService;
    @Resource
    private PdfDocumentContentService pdfDocumentContentService;
    @Resource
    private PdfParseService pdfParseService;
    @Resource
    private OcrConfigChecker ocrConfigChecker;
    @Resource
    private PdfConfig pdfConfig;

    @PostMapping("/upload")
    @Operation(summary = "上传PDF文档")
    public Long upload(@RequestParam("file") MultipartFile file, @RequestParam Long userId) throws Exception {
        // 上传并自动解析、存储内容
        return pdfParseService.parseAndSave(file, userId);
    }

    @GetMapping("/search")
    @Operation(summary = "搜索PDF文档内容")
    public ResponseDTO<List<SearchResultVO>> search(@RequestParam String keyword) {
        // 使用模糊匹配搜索内容表
        QueryWrapper<PdfDocumentContentEntity> wrapper = new QueryWrapper<>();
        wrapper.like("content", keyword);
        List<PdfDocumentContentEntity> contentList = pdfDocumentContentService.list(wrapper);
        // 查询文档元信息
        List<Long> docIds = contentList.stream().map(PdfDocumentContentEntity::getDocumentId).distinct().collect(Collectors.toList());
        List<PdfDocumentEntity> docList = docIds.isEmpty() ? List.of() : pdfDocumentService.listByIds(docIds);
        // 组装结果
        List<SearchResultVO> result = contentList.stream().map(c -> {
            PdfDocumentEntity doc = docList.stream().filter(d -> d.getId().equals(c.getDocumentId())).findFirst().orElse(null);
            return new SearchResultVO(doc, c.getPageNumber(), c.getContent());
        }).collect(Collectors.toList());
        return ResponseDTO.ok(result);
    }

    @GetMapping("/ocr/check")
    @Operation(summary = "检查OCR配置状态")
    public OcrConfigChecker.OcrConfigStatus checkOcrConfig() {
        return ocrConfigChecker.checkOcrConfig(pdfConfig.getTessdataPath());
    }

    @GetMapping("/ocr/config")
    @Operation(summary = "获取OCR配置信息")
    public OcrConfigInfo getOcrConfig() {
        OcrConfigInfo info = new OcrConfigInfo();
        info.setTessdataPath(pdfConfig.getTessdataPath());
        info.setUploadMaxFileSize(pdfConfig.getUploadMaxFileSize());
        info.setUploadMaxRequestSize(pdfConfig.getUploadMaxRequestSize());
        
        // 添加OCR性能配置信息
        PdfConfig.Ocr ocrConfig = pdfConfig.getOcr();
        info.setThreadPoolSize(ocrConfig.getThreadPoolSize());
        info.setImageDpi(ocrConfig.getImageDpi());
        info.setEnableImagePreprocessing(ocrConfig.getEnableImagePreprocessing());
        info.setEnableMultiLanguage(ocrConfig.getEnableMultiLanguage());
        info.setEnableLstmEngine(ocrConfig.getEnableLstmEngine());
        info.setContrastEnhancement(ocrConfig.getContrastEnhancement());
        info.setPageSegMode(ocrConfig.getPageSegMode());
        
        return info;
    }

    // 搜索结果VO
    public static class SearchResultVO {
        public Long documentId;
        public String fileName;
        public Integer pageNumber;
        public String content;
        public SearchResultVO(PdfDocumentEntity doc, Integer pageNumber, String content) {
            this.documentId = doc != null ? doc.getId() : null;
            this.fileName = doc != null ? doc.getFileName() : null;
            this.pageNumber = pageNumber;
            this.content = content;
        }
    }

    // OCR配置信息VO
    public static class OcrConfigInfo {
        private String tessdataPath;
        private Integer uploadMaxFileSize;
        private Integer uploadMaxRequestSize;
        
        // OCR性能配置字段
        private Integer threadPoolSize;
        private Integer imageDpi;
        private Boolean enableImagePreprocessing;
        private Boolean enableMultiLanguage;
        private Boolean enableLstmEngine;
        private Double contrastEnhancement;
        private Integer pageSegMode;

        // Getters and Setters
        public String getTessdataPath() {
            return tessdataPath;
        }

        public void setTessdataPath(String tessdataPath) {
            this.tessdataPath = tessdataPath;
        }

        public Integer getUploadMaxFileSize() {
            return uploadMaxFileSize;
        }

        public void setUploadMaxFileSize(Integer uploadMaxFileSize) {
            this.uploadMaxFileSize = uploadMaxFileSize;
        }

        public Integer getUploadMaxRequestSize() {
            return uploadMaxRequestSize;
        }

        public void setUploadMaxRequestSize(Integer uploadMaxRequestSize) {
            this.uploadMaxRequestSize = uploadMaxRequestSize;
        }

        public Integer getThreadPoolSize() {
            return threadPoolSize;
        }

        public void setThreadPoolSize(Integer threadPoolSize) {
            this.threadPoolSize = threadPoolSize;
        }

        public Integer getImageDpi() {
            return imageDpi;
        }

        public void setImageDpi(Integer imageDpi) {
            this.imageDpi = imageDpi;
        }

        public Boolean getEnableImagePreprocessing() {
            return enableImagePreprocessing;
        }

        public void setEnableImagePreprocessing(Boolean enableImagePreprocessing) {
            this.enableImagePreprocessing = enableImagePreprocessing;
        }

        public Boolean getEnableMultiLanguage() {
            return enableMultiLanguage;
        }

        public void setEnableMultiLanguage(Boolean enableMultiLanguage) {
            this.enableMultiLanguage = enableMultiLanguage;
        }

        public Boolean getEnableLstmEngine() {
            return enableLstmEngine;
        }

        public void setEnableLstmEngine(Boolean enableLstmEngine) {
            this.enableLstmEngine = enableLstmEngine;
        }

        public Double getContrastEnhancement() {
            return contrastEnhancement;
        }

        public void setContrastEnhancement(Double contrastEnhancement) {
            this.contrastEnhancement = contrastEnhancement;
        }

        public Integer getPageSegMode() {
            return pageSegMode;
        }

        public void setPageSegMode(Integer pageSegMode) {
            this.pageSegMode = pageSegMode;
        }
    }
} 